#!/usr/bin/python3

# getcoastline.py - Get OSM coastline information for WS3.0 landclass texture masking
# Copyright (C) 2023  Stuart Buchanan
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

# You will need Python Overpass API - "pip install overpy"

import xml.etree.ElementTree
import os
import shutil
import re
import sys
import collections
import requests
from math import floor

import overpy

PROGNAME = os.path.basename(sys.argv[0])

curr_coast_count = 0
coast_count = 0

def usage(msg, *, exit_status=1, **kwargs):
    help_text = f"""\
ERROR: {msg}

Get OSM coastline information for WS3.0 landclass texture masking

Usage: {PROGNAME} <min-lon> <min-lat> <max-lon> <max-lat> <output-file>

  <min-lon> <min-lat> <max-lon> <max-lat> - bounding box of coastline to retrieve
  <output-file> - Output file to write"""
    print(help_text, **kwargs)
    sys.exit(exit_status)

if len(sys.argv) < 6:
    usage("")

lon0, lat0, lon1, lat1 = map(int, sys.argv[1:5])
output_file = sys.argv[5]


# Single xml tree for output

osm = xml.etree.ElementTree.Element('osm')
osm.attrib = { 'version' : '0.6' }
# Get Coastline data
osm_bbox = ",".join([str(lat0), str(lon0), str(lat1), str(lon1)])

api = overpy.Overpass(url="https://overpass.kumi.systems/api/interpreter")
coast_query = f"""(
    way[\"place\"=\"island\"]({osm_bbox});
    relation[\"place\"=\"island\"]({osm_bbox});
    );(._;>;);out;"""
r = requests.post("https://overpass.kumi.systems/api/interpreter", data=coast_query)
tree = xml.etree.ElementTree.fromstring(r.text)

for child in tree:
    if ((child.tag == "way") or (child.tag == "node")):
        osm.append(child)

    if (child.tag == "way") :
        curr_coast_count = curr_coast_count + 1

print(str(lat) + "," + str(lon) + ": " + str(curr_coast_count) + " pieces of coastline")
coast_count = coast_count + curr_coast_count

# We now have a result containing all the data
tree = xml.etree.ElementTree.ElementTree(osm)
tree.write(output_file)

print(str(lat0) + "," + str(lon0) + " " + str(lat1) + "," + str(lon1))
print("Wrote total of " + str(coast_count) + " pieces of coastline")